package cn.kgc.base.service.impl;

import cn.kgc.base.service.FileService;
import cn.kgc.commons.config.OssFileConfig;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;

/**
 * @description:
 * @author: 石浩杰
 * @date: 2022-11-29 08:40
 */
@Service("ossFileService")
public class OssFileServiceImpl implements FileService {

    @Resource
    private OssFileConfig ossFileConfig;

    @Override
    public String upload(MultipartFile file, String userId, String fileName) {
        String endpoint = ossFileConfig.getEndpoint();
        String accessKeyId = ossFileConfig.getAccessKeyId();
        String accessKeySecret = ossFileConfig.getAccessSecret();
        String bucketName = ossFileConfig.getBucketName();
        String objectName = ossFileConfig.getObjectName();
        String osshost = ossFileConfig.getOsshost();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {

            //获得输入流
            InputStream inputStream = file.getInputStream();
            //重新给objectName属性赋值（文件夹的名字+文件的名字） images/pms/用户id
            fileName=System.currentTimeMillis()+fileName;
            objectName=objectName+"/"+userId+"/"+fileName;
            // 创建PutObject请求。上传文件
            ossClient.putObject(bucketName, objectName, inputStream);
            //ossHost服务器存储图片的路径
            //http://bandu1998.oss-cn-shanghai.aliyuncs.com/
            osshost=osshost+objectName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            return osshost;
        }
    }
}
